/**
 * 路由配置
 */

import Vue from 'vue'
import Router from 'vue-router'
import Login from '../views/Login.vue'
import Test from '../views/test.vue'
import MainTable from '../components/MainTable.vue'
import PatientTags from '../views/PatientTags.vue'
import AdminTable from '../components/AdminTable.vue'
import AccountManager from '../views/AccountManager.vue'
import DictionaryManager from '../views/DictionaryManager.vue'
import { setCookie,setCookie2, getCookie, checkCookie, clearCookie } from '@/utils/cookie';
import { Message } from 'element-ui';
import { Notification } from 'element-ui';

/**
 * 导入utils包下cookie.js的方法
 */
Vue.prototype.$setCookie = setCookie;
Vue.prototype.$setCookie2 = setCookie2;
Vue.prototype.$getCookie = getCookie;
Vue.prototype.$checkCookie = checkCookie;
Vue.prototype.$clearCookie = clearCookie;

Vue.use(Router)
const VueRouterPush = Router.prototype.push
Router.prototype.push = function push (to) {
  return VueRouterPush.call(this, to).catch(err => err)
}

/**
 * 使用axios方法
 */
var axios = require('axios')
Vue.prototype.$axios = axios

const router = new Router({
  mode:'hash',
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login
    },
    {
      path: '/',
      name: '/',
      component: Login
    },
    {
      path: '/Test',
      name: 'Test',
      component: Test
    },
    {
      path: '/MainTable',
      name: 'MainTable',
      component: MainTable,
      children: [{
        path: '/PatientTags',
        component: PatientTags
      },
      {
      path: '/DictionaryManager',
      name: 'DictionaryManager',
      component: DictionaryManager
    },

    ]
    },
    {
      path: '/AdminTable',
      name: 'AdminTable',
      component: AdminTable,
      children: [{
        path: '/AccountManager',
        component: AccountManager
      }]
    },

  ]
});

/**
 * 路由守卫————全局守卫拦截（自动登录，权限访问，未登录不能访问）
 */
router.beforeEach((to, from, next)=>{
  var token = getCookie("token");
  var formdata = new FormData();
  var tokenStr = getCookie("token").split("");
  var targetStr = tokenStr[tokenStr.length-1]
  formdata.append("token",token);

  //判断是否走的是登陆页面
  if(to.name != 'Login' && to.name != '/'){
    //未登录跳转到登录页面
    if(token == '' || token == null){
      Notification({
          title: "您未登录，请先登录！",
          type: "warning",
      });
      next({name:'Login'});
    }else{
      //进入账号管理页面前的判断
      if(to.name == 'AdminTable'){
        //管理员进入账号管理页面
        if(targetStr == "1"){
          next()
        }else{
          //非管理员不能进入账号管理界面
          Notification({
            title: "您没有管理员权限",
            type: "warning",
          });
          return;
        }
      }
    }
  }
  next()

})

export default router

